# 树莓派获取ip 地址
import requests
import json
import time
import http.client
import re
import random
import os
import threading
import socket

# 用户名和密码
username = "qinghao.zeng@goldcorolla.com"  #'976272457@qq.com' # 或是qinghao.zeng@goldcorolla.com 密码一样
password = "Smp_ubuntu"
login_url = "https://dashboard.cpolar.com/login"
# 创建一个会话
session = requests.Session()
# 登录 添加请求头cookie 信息
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
session.headers.update(headers)


# 获取excel数据 判断是否要发送数据到excel
def GetExcelData():
    url = "https://www.kdocs.cn/api/v3/ide/file/cgwc1mzFvTZv/script/V2-36WtVwTP9o6nX614UzRgmZ/sync_task"
    headers = {
        "Content-Type": "application/json",
        "AirScript-Token": "5ffrRM05zIR3TuRkxZlPSe",
    }
    # 当前时间
    data = {"Context": {"argv": {"Type": "GetExcelData"}}}
    # print(data)
    response = requests.post(url, headers=headers, data=json.dumps(data))
    # print(response.text)
    return response.json()

# 获取ip地址 type 0 外网 1 内网
def get_ip(type):
    if type == "0":
        print("获取外网ip")
        url = "http://ip-api.com/json/?lang=zh-CN"
        response = requests.get(url)
        data = response.json()
        # print(data)
        return data["query"]
    elif type == "1":
        print("获取本机内网ip")
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except:
            return "127.0.0.1"
        finally:
            s.close()
        return "127.0.0.1"


# 获取html内容后解析内容
def get_html_content():
    # 先登录
    session = requests.Session()
    get_response = session.get(login_url)
    # 等待3到5秒
    time.sleep(random.randint(2, 6))
    response = session.post(login_url, data={"login": username, "password": password})
    time.sleep(random.randint(1, 3))
    # 获取html内容
    html = session.get("https://dashboard.cpolar.com/status")
    html = html.text
    print("获取html内容")
    # print(html)
    print("正在获取Vpn网络地址")
    # 获取整个table标签内容
    tbody_tags = re.findall(r"<tbody.*?>.*?</tbody>", html, re.S)
    contents = [re.sub(r"<.*?>", "", tag) for tag in tbody_tags]
    for content in contents:
        # 若果有换行符，则删除换行符 空格符 制表符 替换为空
        content = re.sub(r"\n|\t", "", content)
        # 若空格有连续出现150个以上，则替换为换行符
        content = re.sub(r"\s{150,}", "\n", content)
        # 若空格有连续出现78个以上空格替换为\t 并且 去掉前后的空格
        content = re.sub(r"\s{78,}", "\t", content).strip()

    content = re.sub(r"\s{8,}", "\t", content)
    allData = content.split("\t")
    list_json_Data = []
    # print(int(len(allData)/5))
    # index = 0
    for index in range(int(len(allData) / 5)):
        data = {
            "Name": allData[(index * 5)],
            "Content": allData[(index * 5) + 1],
            "Url": allData[(index * 5) + 2],
            "localhost": allData[(index * 5) + 3],
            "Time": allData[(index * 5) + 4],
        }
        index += 1
        # print(data)
        list_json_Data.append(data)
        # list_json_Data 转为字符串
        # list_json_Data = json.dumps(list_json_Data, ensure_ascii=False, indent=4)
        # print(list_json_Data)
        # print(list_json_Data)
    # print(json.dumps(list_json_Data,ensure_ascii=False))
    return json.dumps(list_json_Data, ensure_ascii=False)


# 发送数据到excel
def SendDataToExcel():
    local_ip = get_ip("1")
    _ip = get_ip("0")    
    # cpvpn = get_html_content()
    try:
        cpvpn = Get_Vpn_Loacl_Urls('0')
    except:
        try:
            cpvpn = get_html_content()
        except:
            cpvpn = "获取Vpn网络地址失败"
    finally:
        print("获取Vpn网络地址成功")    
    # print(cpvpn)
    url = "https://www.kdocs.cn/api/v3/ide/file/cgwc1mzFvTZv/script/V2-36WtVwTP9o6nX614UzRgmZ/sync_task"
    headers = {
        "Content-Type": "application/json",
        "AirScript-Token": "5ffrRM05zIR3TuRkxZlPSe",
    }
    local_ip_Data = {"local_ip": local_ip, "ip": _ip}
    # 当前时间
    data = {
        "Context": {
            "argv": {
                "Type": "SetExcelData",
                "local_ip_Data": local_ip_Data,
                "data": cpvpn,
                "Last_Date_Time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            }
        }
    }
    # print(data)
    response = requests.post(url, headers=headers, data=json.dumps(data))

    # print(response.text)
    return response.json()


# 获取本地ip type 0 使用seession, 1 使用requests
def Get_Vpn_Loacl_Urls(type):
    res=""
    loginUrl = "http://localhost:9200/api/v1/user/login"
    payload = {"email": username, "password": password}
    headers = {"content-type": "application/json"}
    if type == "0":
        Local_seesion = requests.Session()
        res = Local_seesion.post(loginUrl, json=payload, headers=headers)
        Authorization = "Bearer " + res.json()["data"]["token"]
        # print(res.json())
        headers = {"content-type": "application/json", "Authorization": Authorization}
        html = Local_seesion.get(
            "http://localhost:9200/api/v1/tunnels", headers=headers
        )
        # 返回的内容是json格式 无需转格式
        html = html.json()
        print(html)
        res= html
    elif type == "1":
        response = requests.request(
            "POST", loginUrl, json=payload, headers={"content-type": "application/json"}
        )
        Authorization = "Bearer " + response.json()["data"]["token"]
        print(response.json())
        headers = {"content-type": "application/json", "Authorization": Authorization}
        response = requests.request(
            "get", "http://localhost:9200/api/v1/tunnels", headers=headers
        )
        html = response.json()
        print(html)
        res= html
    
    list_json_Data = []
    for item in res["data"]["items"]:
        data = {
                "Name": item["name"],
                "Content":item["public_url"],
                "Url":item["status"],
                "localhost":item["publish_tunnels"][0]["addr"],
                "Time": item["publish_tunnels"][0]["create_datetime"],
            }
        list_json_Data.append(data) 
    print(json.dumps(list_json_Data))
    
    # 获取数据返回为json格式
    return json.dumps(list_json_Data)
        # 转为json格式
        # html = json.loads(html)
        # html = (json.dumps(html,ensure_ascii=False))


def RunMain():
    begintime = time.time()
    # 时间 yyyy-mm-dd hh:mm:ss 格式
    print("开始执行" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(begintime)))
    res = SendDataToExcel()
    print(res)
    # 获取json中的result字段
    result = res["data"]["result"]["data"]
    # 等待2s
    # time.sleep(2)
    endtime = time.time()
    print("执行结束" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endtime)))
    print("执行完成耗时" + str(endtime - begintime) + "s")


def test():
    print("test starting....")
    # print(GetExcelData()) 
    print(get_ip("0"))
    print(get_ip("1"))
    # print(get_html_content())
    Get_Vpn_Loacl_Urls("0")
    Get_Vpn_Loacl_Urls("1")
    # SendDataToExcel()
    print("test ending....")


if __name__ == "__main__":  
    # test()
    Isrun=GetExcelData()
    print(Isrun)
    if Isrun["data"]["result"]["data"]["IsNowRun"] == 1:
        RunMain()
        print("执行")
    else:
        print("未执行")

    # print("Last_Update_Time:",result)

    # 调用其他python脚本  这里要注意 win 默认是Python linux 必须为python3
    # os.system("python E:\Hayes\OrigCode\Plugins\Python\Dev.py")
    # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


# [Unit]
# Description=Send_ipTo_Excel  #将本地ip地址发送到指定邮箱
# After=network.target  # 这里填上你这个脚本所需要的前置service，都在/etc/systemd/system/下【这一项可以不写】

# [Service]
# ExecStart=/home/ubuntu/.Hayes_Auto_Satrt/Auto_Start.sh
# Type=simple
# EnvironmentFile=-/home/ubuntu/.Hayes_Auto_Satrt/Auto_Start.sh
# ExecReload=sh /home/ubuntu/.Hayes_Auto_Satrt/Auto_Start.sh
# KillMode=process
# RestartSec=3s
# Restart=on-failure

# [Install]
# WantedBy=multi-user.target
